package com.sudo.api.interceptor;

import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.RetResponse;
import com.sudo.service.admin.service.AdminBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * author：为道日损 2020-04-24 17:35
 */
@Order(3)
@Component
public class UserTokenInterceptor extends AdminBaseService implements HandlerInterceptor {
    /**
     * 请求controller之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String username = HttpUserInfoUtil.getSessionUser(request);
        String userToken = HttpUserInfoUtil.getSessionToken(request);
        String redis_user_token = redisKeys.redisUserToken(username);
        String roleCode = getRoleCodeFromRedisByUsername(username);
        if (null == roleCode) {
            RetResponse.res(response, JsonRes.errorMsg("该用户没有权限"));
            return false;
        }

        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = stringRedisUtil.get(redis_user_token);
            if (StringUtils.isBlank(uniqueToken)) {
                RetResponse.res(response, JsonRes.errorMsg("Token失效，请重新登录"));
                return false;
            } else {
                /*if (!uniqueToken.equals(userToken)) {
                    RetResponse.res(response, JsonRes.errorMsg("账号可能在异地登录"));
                    return false;
                }*/
            }
        } else {
            RetResponse.res(response, JsonRes.errorMsg("Token失效，请重新登录"));
            return false;
        }
        /*
         * false：请求被拦截，被驳回，验证出现问题
         * true：请求验证校验ok，可以放行
         */
        stringRedisUtil.expire(redis_user_token, 7200, TimeUnit.SECONDS);
        return true;
    }

}
